package com.gitee.huanminabc.utils_tools.security.authority;

import com.gitee.huanminabc.utils_tools.security.service.RoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 获取当前请求所需要的角色列表
 *
 * @author huanmin
 * @date 2024/1/24
 */

@Component
@Slf4j
public class SecurityInvocationSecurityMetadataSourceService implements FilterInvocationSecurityMetadataSource {
    @Autowired
    private RoleService roleService;
    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {

        String requestUrl = ((FilterInvocation) object).getRequestUrl();
        //如果查询不到对应的url权限则默认为登录即可访问
        List<String> roles = roleService.getRoles(requestUrl);
        log.debug("requestUrl >> {}，roles：{}", requestUrl, roles);
        return roles.stream().map((role)-> (ConfigAttribute) new SecurityConfig(role)).collect(Collectors.toSet());
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return new HashSet<>();
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }

}
